package com.chinatechstar.component.commons.service;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.UUID;

public class AliyunOssService {
//    private static final String ACCESS_KEY_ID = "LTAIILtBOcireXCs";
    private static final String ACCESS_KEY_ID = "LTAI5tKjnpGPDGVH6Lb9gjPv";
//    private static final String ACCESS_KEY_SECRET = "KzejzE8cpNYx6K9UDsd12wF0w3y8Lj";
    private static final String ACCESS_KEY_SECRET = "OzhSNTproJ7ajueaYoCRkK2YdpsFv9";

    public String upload(String fileName, byte[] content) {
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        String bucketName = "ld-cloud2";
        String dirName = UUID.randomUUID().toString();
        String objectName = "upload/" + dirName + "/" + fileName;
        OSS ossClient = new OSSClientBuilder().build(endpoint, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        try {
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content));
            return "https://ld-cloud2.oss-cn-hangzhou.aliyuncs.com/upload/" + dirName + "/" + fileName;
        } catch (OSSException oe) {
            throw oe;
        } catch (ClientException ce) {
            throw ce;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public String upload(String filePath){
        return upload(new File(filePath));
    }

    public String upload(File file) {
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        String bucketName = "ld-cloud2";
        String dirName = UUID.randomUUID().toString();
        String fileName = file.getName();
        String objectName = "upload/" + dirName + "/" + fileName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        try {
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, file);
            return "https://ld-cloud2.oss-cn-hangzhou.aliyuncs.com/upload/" + dirName + "/" + fileName;
        } catch (OSSException oe) {
            throw oe;
        } catch (ClientException ce) {
            throw ce;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public String uploadMultipartFile(MultipartFile file) {
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        String bucketName = "ld-cloud2";
        String dirName = UUID.randomUUID().toString();
        String fileName = file.getOriginalFilename();
        String objectName = "upload/" + dirName + "/" + fileName;
        OSS ossClient = new OSSClientBuilder().build(endpoint, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        try {
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, file.getInputStream());
            String rtnUrl = "https://ld-cloud2.oss-cn-hangzhou.aliyuncs.com/upload/" + dirName + "/" + URLEncoder.encode(fileName, "utf-8");
            return rtnUrl;
        } catch (OSSException oe) {
            throw oe;
        } catch (ClientException ce) {
            throw ce;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public InputStream download(String url) {
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        String bucketName = "ld-cloud2";
        String objectName = null;
        try {
            objectName = URLDecoder.decode(url, "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        try {
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            return ossObject.getObjectContent();
        } catch (OSSException oe) {
            throw oe;
        } catch (ClientException ce) {
            throw ce;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public void downloadUsingNIO(String urlStr, String file) {
        try {
            URL url = new URL(urlStr);
            ReadableByteChannel rbc = Channels.newChannel(url.openStream());
            FileOutputStream fos = new FileOutputStream(file);
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            fos.close();
            rbc.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public InputStream downloadStreamUsingNIO(String urlStr) {
        try {
            URL url = new URL(urlStr);
            InputStream inputStream=url.openStream();
            return inputStream;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

   /* public OssTokenResponse getOssToken() {
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5tD638EKMPFB9K6j9PhH", "lqlz4Vl6GZd6mljqaMSVzGAL3TKrcd");
        DefaultAcsClient client = new DefaultAcsClient(profile);
        AssumeRoleRequest request = new AssumeRoleRequest();
        request.setVersion("2015-04-01");
        request.setMethod(MethodType.POST);
        request.setProtocol(ProtocolType.HTTPS);

        request.setRoleArn("acs:ram::1742551687382266:role/ramosstest");
        request.setRoleSessionName("alice-001");
        request.setPolicy("{\n" +
                "  \"Statement\": [\n" +
                "    {\n" +
                "      \"Action\": [\n" +
                "        \"oss:*\"\n" +
                "      ],\n" +
                "      \"Effect\": \"Allow\",\n" +
                "      \"Resource\": [\"acs:oss:*:*:*\"]\n" +
                "    }\n" +
                "  ],\n" +
                "  \"Version\": \"1\"\n" +
                "}");
        request.setDurationSeconds(900L);
        AssumeRoleResponse stsResponse;
        try {
            stsResponse = client.getAcsResponse(request);
        } catch (com.aliyuncs.exceptions.ClientException e) {
            e.printStackTrace();
            throw new WnyRestException();
        }
        OssTokenResponse response = new OssTokenResponse();
        response.setStatus("200");
        response.setAccessKeyId(stsResponse.getCredentials().getAccessKeyId());
        response.setAccessKeySecret(stsResponse.getCredentials().getAccessKeySecret());
        response.setSecurityToken(stsResponse.getCredentials().getSecurityToken());
        response.setExpiration(stsResponse.getCredentials().getExpiration());
        return response;
    }
*/
    public String airShipUploadToOss(MultipartFile file) {
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        String bucketName = "wny-upload2";
//        String dirName = UUID.randomUUID().toString();
        String fileName = file.getOriginalFilename();
//        String objectName = "lims/airShip/" + dirName + "/" + fileName;
        String objectName = "lims/airShip/" + fileName;
        OSS ossClient = new OSSClientBuilder().build(endpoint, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        try {
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, file.getInputStream());
            return "https://wny-upload2.oss-cn-hangzhou.aliyuncs.com/lims/airShip/" + URLEncoder.encode(fileName, "utf-8");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
